package com.maysev.myjob_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maysev.myjob_backend.common.R;
import com.maysev.myjob_backend.dto.RecruitmentDto;
import com.maysev.myjob_backend.entity.Category;
import com.maysev.myjob_backend.entity.Company;
import com.maysev.myjob_backend.entity.Recruitment;
import com.maysev.myjob_backend.entity.Subcategory;
import com.maysev.myjob_backend.service.*;
import com.maysev.myjob_backend.utils.StringArrayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 五七
 * @create 2023-03-26 17:45
 * @description:
 */
@RestController
@Slf4j
@CrossOrigin("http://localhost:8082")
@RequestMapping("/recruitment")
public class RecruitmentController {
    @Autowired
    private RecruitmentService recruitmentService;
    
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SubcategoryService subcategoryService;

    @Autowired
    private CompanyService companyService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param title
     * @return
     */
    @GetMapping("/page")
    private R<Page> getRecruitments(@RequestParam int page, @RequestParam int pageSize, @RequestParam(required = false) Long recruiterId, @RequestParam String title, @RequestParam String education, @RequestParam String category , @RequestParam String status){
        Page<Recruitment> recruitmentPage = new Page<>(page,pageSize);
        Page<RecruitmentDto> recruitmentDtoPage = new Page<>();

        LambdaQueryWrapper<Recruitment> queryWrapper = new LambdaQueryWrapper<>();
        //搜索框
        queryWrapper.like(title != null,Recruitment::getTitle,title);
        queryWrapper.orderByDesc(Recruitment::getUpdateTime);
        //对学历,分类进行解码
        String decodedCategory = null;
        String decodedEducation = null;
        try {
            decodedCategory = URLDecoder.decode(category, "UTF-8");
            decodedEducation = URLDecoder.decode(education, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        //分类查询
        queryWrapper.eq(decodedCategory != "",Recruitment::getCategory,decodedCategory);
        //学历查询
        queryWrapper.eq(decodedEducation != "",Recruitment::getEducation,decodedEducation);
        //招聘人id
        queryWrapper.eq(recruiterId != null, Recruitment::getRecruiterId,recruiterId);
        //状态查询
        queryWrapper.eq(status != "",Recruitment::getStatus,status);

        recruitmentService.page(recruitmentPage,queryWrapper);

        BeanUtils.copyProperties(recruitmentPage,"records");

        List<Recruitment> records = recruitmentPage.getRecords();

//        String finalCategoryName = categoryName;
//
        List<RecruitmentDto> collect = records.stream().map((item) -> {
            RecruitmentDto recruitmentDto = new RecruitmentDto();

            BeanUtils.copyProperties(item, recruitmentDto);
            String category1 = item.getCategory();
            String education1 = item.getEducation();
            String dateCount = item.getDateCount();
            Long recruiterId1 = item.getRecruiterId();


            String[] array = StringArrayUtils.toStringArray(category1);
            String[] educations = StringArrayUtils.toStringArray(education1);
            String[] dateCounts = StringArrayUtils.toStringArray(dateCount);


            String educationName = educations[0].replace("\"", "");
            String dateCountNumber = dateCounts[0].replace("\"", "");
            String name = "";


            LambdaQueryWrapper<Company> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Company::getUserId,recruiterId1);

            Company company = companyService.getOne(queryWrapper1);
            String companyName = company.getName();
            String companyAvatar = company.getAvatar();

            if (array.length == 1){
                Long categoryId =  Long.parseLong(array[0].replace("\"", ""));
                Category category2 = categoryService.getById(categoryId);
                 name = category2.getName();
            } else if (array.length == 2) {
                Long categoryId =  Long.parseLong(array[1].replace("\"", ""));
                Subcategory category2 = subcategoryService.getById(categoryId);
                 name = category2.getName();
            }
            recruitmentDto.setEducationName(educationName);
            recruitmentDto.setSubcategoryName(name);
            recruitmentDto.setDateCountNumber(dateCountNumber);
            recruitmentDto.setCompanyAvatar(companyAvatar);
            recruitmentDto.setCompanyName(companyName);
//
            return recruitmentDto;
        }).collect(Collectors.toList());
        recruitmentDtoPage.setPages(recruitmentPage.getPages());
        recruitmentDtoPage.setTotal(recruitmentPage.getTotal());
        recruitmentDtoPage.setRecords(collect);

        return R.success(recruitmentDtoPage);
    }


    /**
     * 保存招聘信息
     * @param recruitment
     * @return
     */
    @PostMapping("/saveRec")
    private R<String> savaRecruitment(@RequestBody Recruitment recruitment){
        log.info(recruitment.toString());
        recruitment.setStatus("0");
        recruitmentService.save(recruitment);
        return R.success("保存成功");
    }

    /**
     * 保存并发布招聘信息
     * @param recruitment
     * @return
     */
    @PostMapping("/publishRec")
    private R<String> publishRecruitment(@RequestBody Recruitment recruitment){
        log.info(recruitment.toString());
        recruitment.setStatus("1");
        recruitmentService.save(recruitment);
        return R.success("发布成功");
    }

    /**
     * 根据id查询招聘信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    private R<Recruitment> getRecruitmentById(@PathVariable Long id){
        log.info("本次查询的兼职信息的id:{}",id);
        Recruitment recruitment = recruitmentService.getById(id);
        return R.success(recruitment);
    }

    /**
     * 更新招聘信息
     * @param recruitment
     * @return
     */
    @PutMapping("/updateRec")
    private R<String> updateRecruitmentById(@RequestBody Recruitment recruitment){
        recruitmentService.updateById(recruitment);
        return R.success("更改成功");
    }

    /**
     * 更新并发布
     * @param recruitment
     * @return
     */
    @PutMapping("/updateAndPublishRec")
    private R<String> updateAndPublishRecruitmentById(@RequestBody Recruitment recruitment){
        recruitment.setStatus("1");
        recruitmentService.updateById(recruitment);
        return R.success("更改成功");
    }


    /**
     * 根据id删除招聘信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    private R<String> deleteRecInfoById(@PathVariable Long id){
        recruitmentService.removeById(id);
        return R.success("删除成功");
    }


}
